<script lang="ts" setup>
import type { Rule } from 'ant-design-vue/es/form';

import { onMounted, ref } from 'vue';

import { message } from 'ant-design-vue';

import { getAllUserMenu } from '#/api';

import { PlusSquareFilled, MinusSquareFilled } from '@ant-design/icons-vue';

// 定义菜单项接口
interface MenuItem {
  id: number;
  parentId: null | number;
  name: string;
  path: string;
  component: string;
  redirect: string;
  title: null | string;
  icon: null | string;
  levels: number;
  meta: {
    icon: string;
    title: string;
  };
  status?: boolean;
  key?: number | string;
  children?: MenuItem[];
}

// 表单数据接口
interface FormState {
  name: string;
  path: string;
  component: string;
  redirect: string;
  icon: string;
  title: string;
  levels: number;
  parentId?: null | number;
}

const loading = ref(false);
const tableData = ref<MenuItem[]>([]);
const expandedRowKeys = ref<(number | string)[]>([]);
const visible = ref(false);
const formRef = ref();
const currentParentId = ref<null | number>(null);
const formState = ref<FormState>({
  name: '',
  path: '',
  component: '',
  redirect: '',
  icon: '',
  title: '',
  levels: 1,
  parentId: null,
});

// 表单验证规则
const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件地址', trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  icon: [{ required: true, message: '请输入图标', trigger: 'blur' }],
  levels: [{ required: true, message: '请输入层级', trigger: 'blur' }],
};

// 表格列定义
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    align: 'left',
  },
  {
    title: '标题',
    dataIndex: ['meta', 'title'],
    key: 'title',
  },
  {
    title: '路由路径',
    dataIndex: 'path',
    key: 'path',
  },
  {
    title: '组件地址',
    dataIndex: 'component',
    key: 'component',
  },
  {
    title: '路由重定向',
    dataIndex: 'redirect',
    key: 'redirect',
  },
  {
    title: '图标',
    dataIndex: ['meta', 'icon'],
    key: 'icon',
  },
  {
    title: '层级',
    dataIndex: 'levels',
    key: 'levels',
    width: 80,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    slots: { customRender: 'action' },
  },
];
// 处理API返回的数据，确保符合MenuItem类型
const processMenuData = (data: any[]): MenuItem[] => {
  const result: MenuItem[] = [];

  for (const item of data) {
    const processedItem = {
      ...item,
      key: item.id || item.path,
      status: true,
    } as MenuItem;

    // 如果存在children且不为空数组，则递归处理
    if (item.children && item.children.length > 0) {
      // 递归处理子节点
      const processedChildren = processMenuData(item.children);

      // 如果处理后的children不为空，则保留children属性
      if (processedChildren.length > 0) {
        // 检查每个子节点的children是否为空
        const validChildren = processedChildren
          .map((child) => {
            if (child.children && child.children.length > 0) {
              // 递归处理更深层级的子节点
              const grandChildren = processMenuData(child.children);
              if (grandChildren.length > 0) {
                child.children = grandChildren;
                return child;
              }
              return { ...child, children: undefined };
            }
            return child;
          })
          .filter((child) => child.children !== undefined);

        if (validChildren.length > 0) {
          processedItem.children = validChildren;
        }
      }
    }

    result.push(processedItem);
  }

  return result;
};
const getTable = async () => {
  loading.value = true;
  try {
    const res = await getAllUserMenu();
    if (res && Array.isArray(res)) {
      tableData.value = processMenuData(res);
    }
  } catch {
    // 错误处理
  } finally {
    loading.value = false;
  }
};

// 展开/折叠所有行
const toggleExpandAll = () => {
  if (expandedRowKeys.value.length > 0) {
    expandedRowKeys.value = [];
  } else {
    // 获取所有有子节点的行的key
    const getAllKeys = (data: MenuItem[]): (number | string)[] => {
      const keys: (number | string)[] = [];
      for (const item of data) {
        if (item.children && item.children.length > 0) {
          keys.push(item.key as number | string, ...getAllKeys(item.children));
        }
      }
      return keys;
    };
    expandedRowKeys.value = getAllKeys(tableData.value);
  }
};

// 打开新增弹窗
const showModal = (parentId?: number) => {
  currentParentId.value = parentId || null;
  formState.value = {
    name: '',
    path: '',
    component: '',
    redirect: '',
    icon: '',
    title: '',
    levels: parentId ? 2 : 1,
    parentId: parentId || null,
  };
  visible.value = true;
};

// 关闭弹窗
const handleCancel = () => {
  visible.value = false;
  formRef.value?.resetFields();
  currentParentId.value = null;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    // 这里添加提交逻辑
    message.success('提交成功');
    handleCancel();
    getTable();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields();
};

onMounted(() => {
  getTable();
});
</script>

<template>
  <div>
    <a-card title="菜单树形表格" :bordered="false">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showModal()">新增一级菜单</a-button>
          <a-button type="primary" @click="getTable">刷新数据</a-button>
          <a-button @click="toggleExpandAll">
            {{ expandedRowKeys.length > 0 ? '折叠所有' : '展开所有' }}
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        bordered
        size="middle"
        :row-key="(record: MenuItem) => record.key as string"
        :indent-size="16"
        :expanded-row-keys="expandedRowKeys"
        @expanded-rows-change="
          (keys: (string | number)[]) => (expandedRowKeys = keys)
        "
      >
        <template #expandIcon="{ expanded, record, onExpand }">
          <span
            v-if="record.children && record.children.length > 0"
            @click="(e: Event) => onExpand(record, e)"
            style="cursor: pointer"
            class="mr-2"
          >
            <MinusSquareFilled v-if="expanded" />
            <PlusSquareFilled v-else />
          </span>
          <span v-else style="padding-left: 16px"></span>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button type="link" @click="showModal(record.id)">
              新增下级
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增弹窗 -->
    <a-modal
      v-model:visible="visible"
      :title="currentParentId ? '新增下级菜单' : '新增一级菜单'"
      @cancel="handleCancel"
      :footer="null"
    >
      <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="路由路径" name="path">
          <a-input
            v-model:value="formState.path"
            placeholder="请输入路由路径"
          />
        </a-form-item>
        <a-form-item label="组件地址" name="component">
          <a-input
            v-model:value="formState.component"
            placeholder="请输入组件地址"
          />
        </a-form-item>
        <a-form-item label="路由重定向" name="redirect">
          <a-input
            v-model:value="formState.redirect"
            placeholder="请输入路由重定向"
          />
        </a-form-item>
        <a-form-item label="标题" name="title">
          <a-input v-model:value="formState.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item label="图标" name="icon">
          <a-input v-model:value="formState.icon" placeholder="请输入图标" />
        </a-form-item>
        <a-form-item label="层级" name="levels">
          <a-input-number v-model:value="formState.levels" :min="1" disabled />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.ant-table-wrapper {
  width: 100%;
}
</style>
